<template>
  <div>
    <!-- 1.页面展示区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 1.1 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="文章分类">
            <el-select placeholder="请选择分类" v-model="q.cate_id">
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态">
            <el-select placeholder="请选择状态" v-model="q.state">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="initArtList">筛选</el-button>
            <el-button type="success" @click="doReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="addVisible = true"
          >发表文章</el-button
        >
      </div>

      <!-- 1.2 文章表格区域 -->
      <el-table :data="artList" style="width: 100%">
        <el-table-column label="文章标题" width="180">
          <!-- 作用域插槽获取文章id -->
          <template v-slot="obj">
            <el-link type="primary" @click="doDetail(obj.row.id)">{{
              obj.row.title
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类" width="180">
        </el-table-column>
        <el-table-column label="发表时间">
          <!-- 使用作用域插槽获取当前tr对应的对象 -->
          <template v-slot="obj">
            <span>{{ formatTime(obj.row.pub_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态"> </el-table-column>
        <el-table-column label="操作">
          <!-- 使用作用域插槽获取文章id -->
          <template v-slot="obj">
            <el-button type="danger" @click="doDelete(obj.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 1.3 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 2.发表文章对话框 -->
    <el-dialog title="发表文章" :visible.sync="addVisible" fullscreen>
      <el-form>
        <!-- 2.1 标题 -->
        <el-form-item label="文章标题" label-width="80px">
          <el-input
            placeholder="请输入文章标题"
            v-model="addForm.title"
          ></el-input>
        </el-form-item>
        <!-- 2.2 文章分类 -->
        <el-form-item label="文章分类" label-width="80px">
          <el-select placeholder="请选择活动区域" v-model="addForm.cate_id">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 2.3 文章内容 -->
        <el-form-item label="文章内容" label-width="80px">
          <quillEditor v-model="addForm.content"></quillEditor>
        </el-form-item>
        <!-- 2.4 文章封面 -->
        <el-form-item label="文章封面" label-width="80px">
          <img
            src="@/assets/images/avatar.jpg"
            alt=""
            ref="imgRef"
            width="200px"
          />
          <br />
          <input
            type="file"
            style="display:none"
            ref="iptRef"
            @change="doChange"
          />
          <el-button type="primary" plain @click="$refs.iptRef.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <!-- 2.5 操作按钮 -->
        <el-form-item label="  " label-width="80px">
          <el-button type="primary" @click="addArticle('已发布')"
            >发布</el-button
          >
          <el-button @click="addArticle('草稿')">存草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 3.文章详情对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="detailDialog"
      width="80%"
    >
      <h1>{{ artDetail.title }}</h1>
      <div>
        <span>作者:{{ artDetail.nickname }}</span>
        <span>发布时间:{{ formatTime(artDetail.pub_date) }}</span>
        <span>所属分类:{{ artDetail.cate_name }}</span>
        <span>状态:{{ artDetail.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <img :src=" 'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img " alt="">
      <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
//导入富文本编辑器插件
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
//导入moment.js
import moment from "moment";
//设置语言(国际化)
moment.locale("zh-cn");

export default {
  name: "ArtList",
  //注册组件
  components: {
    quillEditor
  },
  //1.数据
  data() {
    return {
      //1.1 发表文章对话框
      addVisible: false,
      //1.2 发表文章数据
      addForm: {
        title: "",
        cate_id: "",
        content: "",
        state: "",
        cover_img: ""
      },
      //1.3 文章分类列表
      cateList: [],
      //1.4 查询文章参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: ""
      },
      //1.5 文章列表
      artList: [],
      //1.6 文章总数量
      total: 0,
      //1.7 文章详情
      artDetail: {},
      //1.7 文章详情对话框布尔属性
      detailDialog: false
    };
  },
  //2.事件和方法
  methods: {
    //2.1 表单change事件
    doChange(e) {
      //(1)获取文件
      const file = e.target.files[0];
      //(2)如果有选择
      if (file) {
        //(2.1)添加到data
        this.addForm.cover_img = file;
        //(2.2)生成url 并 显示到img的src属性
        this.$refs.imgRef.src = URL.createObjectURL(file);
      }
    },
    //2.2 发表文章
    async addArticle(state) {
      //(1)绑定参数
      this.addForm.state = state;
      //(2)创建FormData对象(有文件的接口必须要使用: FormData)
      const fd = new FormData();
      /* 把data中的数据,添加到FormData中 */
      for (let key in this.addForm) {
        fd.append(key, this.addForm[key]);
      }
      //(3)发送ajax,参数是formdata
      const { data: res } = await this.$axios.post("/my/article/add", fd);
      console.log(res);
      //(4)发表成功 : 弹窗消失,刷新文章列表
      this.$message.success(res.message);
      if (res.code === 0) {
        this.addVisible = false;
        //刷新列表
        this.initArtList();
      }
    },
    //2.3 获取文章列表
    async initArtList() {
      //发送ajax
      const { data: res } = await this.$axios.get("/my/article/list", {
        params: this.q
      });
      console.log(res);
      //绑定到data
      this.artList = res.data;
      this.total = res.total;
      //假如总共有 10条数据,每页两条。 此时总页数 10/2 = 5
      //当我们删除2条数据之后,总数据变成8， 此时真正总页数 8/2 = 4
      //如果pagenum还是5就会请求不到第五页数据。
      //判断 如果当前pagenum 超过 总数/每页条数,就需要自减,并重新请求第四页数据
      if( this.q.pagenum > Math.ceil(this.total/this.q.pagesize) ){
        this.q.pagenum--
        this.initArtList()
      } 
    },
    //2.4 过滤时间格式
    formatTime(time) {
      return moment(time).format("MMMM Do YYYY, h:mm:ss");
    },
    //2.5 分页组件size变化
    handleSizeChange(val) {
      // console.log(val)
      //(1)修改每页条数
      this.q.pagesize = val;
      //(2)刷新列表
      this.initArtList();
    },
    //2.6 分页组件page变化
    handleCurrentChange(page) {
      // console.log(page)
      //(1)修改页码
      this.q.pagenum = page;
      //(2)刷新列表
      this.initArtList();
    },
    //2.7 重置筛选内容
    doReset() {
      //重置筛选对象
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: ""
      };
      //刷新文章列表
      this.initArtList();
    },
    //2.8 查看文章详情
    async doDetail(id) {
      //(1)获取文章详细信息
      const { data: res } = await this.$axios.get("/my/article/info", {
        params: { id }
      });
      console.log(res);
      //(2)绑定到data
      this.artDetail = res.data;
      //(3)弹出对话框
      this.detailDialog = true
    },
    //2.9 删除文章
    async doDelete(id){
      //(1)发送ajax
      const {data:res} = await this.$axios.delete('/my/article/info',{ params:{id} } )
      this.$message.success(res.message)
      //(2)刷新列表
      this.initArtList()
    }
  },
  //3.created钩子
  async created() {
    //3.1 发送ajax请求文章分类 (因为这个请求页面只需要发一次，所以写在created钩子里)
    const { data: res } = await this.$axios.get("/my/cate/list");
    //绑定到data
    this.cateList = res.data;
    //3.2 发送ajax请求文章列表 (这个请求需要发很多次，所以封装函数调用)
    this.initArtList();
  }
};
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

/deep/ .ql-editor {
  min-height: 300px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top: 15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
